package com.heima.admin.gateway.filter;


import com.heima.admin.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
@Order(1)
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.判断当前请求是否为登录请求，是则放行，不是则判断是否有token
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String url = request.getURI().getPath();
        if(url.contains("/login/in")){
            return chain.filter(exchange);
        }

        //2.获取请求头jwt的token
        String token = request.getHeaders().getFirst("token");
           //如果token不存在，向用户提示错误信息
        if (StringUtils.isBlank(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        try {
            //3.校验token令牌信息是否正确
            Claims claims = AppJwtUtil.getClaimsBody(token);
            //-1 & 0 有效    1 & 2 失效
            int verifyToken = AppJwtUtil.verifyToken(claims);
            if (verifyToken > 0){
                //如果失效或者不正确，提示用户错误信息
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //解析token
            Integer id = claims.get("id", Integer.class);
            log.info("header token id:{}, URL:{}", id, request.getURI().getPath());

            //4.id下放到head各个微服务中
            ServerHttpRequest httpRequest = request.mutate()
                    .headers(httpHeaders -> {
                        httpHeaders.add("userId", String.valueOf(id));
                    }).build();
            exchange.mutate().request(httpRequest).build();
        } catch (Exception e) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //5.返回结果
        return chain.filter(exchange);
    }
}
